layui.config({
    base: "../../js/"
}).extend({
    "utilObj": "utilObj"
});
layui.use(['form', 'utilObj', 'layer'], function () {
    var form = layui.form
    layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        utilObj = layui.utilObj;
    var addUserUrl = "cms/user/addNewAdminUser";
    var updateUserUrl = "cms/user/updateAdminUser";
    var usernameExg = "/^[a-zA-Z]\\w{3,15}$/ig/";
    form.on("submit(addUser)", function (data) {
        var userId = $('.user-id').val();
        var userName = $('.userName').val();
        var email = $('.email').val();
        var userPhone = $('.userPhone').val();
        var userPwd = $('.password').val();
        var userState = data.field.userState;
        var userRole = data.field.userRole;

        var requestData = {
            userName: userName,
            chineseName: email,
            password: userPwd,
            state: userState,
            phone: userPhone,
            role: userRole
        }
        if (userId) {
            requestData.userId = userId;
            operatorUser(requestData, updateUserUrl);
        } else {
            operatorUser(requestData, addUserUrl);
        }
        return false;
    });
    form.verify({
        title: function (value) {
            if (value.length < 5) {
                return '标题至少得5个字符';
            }
        },
        usernaem: [usernameExg, '用户名长度为4-18个字符，以字母开头，包含字符/数字/下划线'],
        pass: [/(.+){8,20}$/, '密码必须8到20位'],
        configpass:

            function (value) {
                var pass = $('.password').val();
                var confirmPass = $('.confirm-password').val();
                if (pass !== confirmPass) {
                    return '两次密码输入不一致';
                }
            }
    })
    ;

    function operatorUser(data, requestUrl) {
        utilObj.showLoading();
        utilObj.ajax({
            url: requestUrl,
            type: "POST",
            data: data,
            success: function (data) {
                console.log(data);
                utilObj.hideLoading();
                setTimeout(function () {
                    top.layer.msg("操作成功！");
                    layer.closeAll("iframe");
                    //刷新父页面
                    parent.location.reload();
                }, 1000);
            },
            error: function (err) {
                console.log(err);
                utilObj.hideLoading();
            }
        });
    }

});